<template>
	<view class="resume-container">
		<view class="header">
			<text class="title">AI简历生成</text>
		</view>
		
		<!-- 用户信息表单 -->
		<view class="form-container" v-if="!resumeGenerated">
			<view class="form-item">
				<text class="label">姓名</text>
				<input class="input" v-model="userInfo.name" placeholder="请输入您的姓名" />
			</view>
			
			<view class="form-item">
				<text class="label">年龄</text>
				<input class="input" v-model="userInfo.age" placeholder="请输入您的年龄" type="number" />
			</view>
			
			<view class="form-item">
				<text class="label">专业</text>
				<input class="input" v-model="userInfo.major" placeholder="请输入您的专业" />
			</view>
			
			<view class="form-item">
				<text class="label">学历</text>
				<picker class="input" @change="bindEducationChange" :value="educationIndex" :range="educationOptions">
					<view class="picker-text">{{ educationOptions[educationIndex] }}</view>
				</picker>
			</view>
			
			<view class="form-item">
				<text class="label">求职意向</text>
				<input class="input" v-model="userInfo.jobIntention" placeholder="请输入您的求职意向" />
			</view>
			
			<view class="form-item">
				<text class="label">工作经验(年)</text>
				<input class="input" v-model="userInfo.experience" placeholder="请输入您的工作经验" type="number" />
			</view>
			
			<view class="form-item">
				<text class="label">技能特长</text>
				<textarea class="textarea" v-model="userInfo.skills" placeholder="请输入您的技能特长，多个技能用逗号分隔" />
			</view>
			
			<view class="form-item">
				<text class="label">自我评价</text>
				<textarea class="textarea" v-model="userInfo.selfEvaluation" placeholder="请输入您的自我评价" />
			</view>
			
			<button class="submit-btn" @click="generateResume" :disabled="isGenerating">{{ isGenerating ? '生成中...' : '生成简历' }}</button>
		</view>
		
		<!-- 生成的简历展示 -->
		<scroll-view v-if="resumeGenerated" class="resume-result-container" scroll-y="true">
			<!-- 美化后的简历 -->
			<view class="resume-result">
				<view class="resume-header">
					<text class="resume-title">{{ resumeData.title || '个人简历' }}</text>
				</view>
				
				<view class="resume-section">
					<text class="section-title">基本信息</text>
					<view class="info-row">
						<text class="info-label">姓名：</text>
						<text class="info-value">{{ userInfo.name }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">年龄：</text>
						<text class="info-value">{{ userInfo.age }}岁</text>
					</view>
					<view class="info-row">
						<text class="info-label">学历：</text>
						<text class="info-value">{{ educationOptions[educationIndex] }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">专业：</text>
						<text class="info-value">{{ userInfo.major }}</text>
					</view>
				</view>
				
				<view class="resume-section">
					<text class="section-title">求职意向</text>
					<view class="info-row">
						<text class="info-value">{{ userInfo.jobIntention }}</text>
					</view>
				</view>
				
				<view class="resume-section">
					<text class="section-title">专业技能</text>
					<view class="info-row" v-for="(skill, index) in resumeData.skills" :key="index">
						<text class="info-value skill-item">• {{ skill }}</text>
					</view>
				</view>
				
				<view class="resume-section">
					<text class="section-title">工作经历</text>
					<view class="experience-item" v-for="(exp, index) in resumeData.workExperience" :key="index">
						<text class="exp-title">{{ exp.title }}</text>
						<text class="exp-time">{{ exp.time }}</text>
						<text class="exp-desc">{{ exp.description }}</text>
					</view>
				</view>
				
				<view class="resume-section">
					<text class="section-title">教育背景</text>
					<view class="education-item" v-for="(edu, index) in resumeData.education" :key="index">
						<text class="edu-school">{{ edu.school }}</text>
						<text class="edu-time">{{ edu.time }}</text>
						<text class="edu-major">{{ edu.major }}</text>
					</view>
				</view>
				
				<view class="resume-section">
					<text class="section-title">自我评价</text>
					<view class="info-row">
						<text class="info-value">{{ resumeData.selfEvaluation }}</text>
					</view>
				</view>
				
				<!-- AI原始回答展示区域 -->
<!-- 				<view class="resume-section ai-response-section">
					<text class="section-title">AI生成内容</text>
					<view class="ai-response-container">
						<text class="ai-response-text">{{ aiResponseText }}</text>
					</view>
				</view> -->
				
				<view class="button-group">
					<button class="back-btn" @click="resetForm">返回修改</button>
					<!-- <button class="share-btn" @click="shareResume">分享简历</button> -->
				</view>
			</view>
		</scroll-view>
		
		<!-- 加载指示器 -->
		<view class="loading-container" v-if="isGenerating">
			<view class="loading-spinner"></view>
			<text class="loading-text">AI正在生成您的简历，请稍候...</text>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useUserStore } from '@/stores/api.js';

const userStore = useUserStore();

// 用户信息表单数据
const userInfo = reactive({
	name: '',
	age: '',
	major: '',
	jobIntention: '',
	experience: '',
	skills: '',
	selfEvaluation: ''
});

// 学历选项
const educationOptions = ['高中', '大专', '本科', '硕士', '博士'];
const educationIndex = ref(2); // 默认选择本科

// 状态变量
const isGenerating = ref(false);
const resumeGenerated = ref(false);
const aiResponseText = ref(''); // 存储AI的原始回答

// 生成的简历数据
const resumeData = reactive({
	title: '',
	skills: [],
	workExperience: [],
	education: [],
	selfEvaluation: ''
});

// 学历选择器变更事件
function bindEducationChange(e) {
	educationIndex.value = e.detail.value;
}

// 生成简历
async function generateResume() {
	// 表单验证
	if (!userInfo.name || !userInfo.age || !userInfo.major || !userInfo.jobIntention) {
		uni.showToast({
			title: '请填写必要的信息',
			icon: 'none'
		});
		return;
	}
	
	// 设置生成中状态
	isGenerating.value = true;
	
	try {
		// 准备发送到后端的数据
		const requestData = {
			message: `请根据以下信息生成一份专业的简历，包括个人基本信息、教育背景、工作经历、专业技能和自我评价。请以JSON格式返回，包含以下字段：title(简历标题)、skills(技能数组)、workExperience(工作经历数组，每项包含title、time、description)、education(教育背景数组，每项包含school、time、major)、selfEvaluation(自我评价)。\n\n个人信息：\n姓名：${userInfo.name}\n年龄：${userInfo.age}\n专业：${userInfo.major}\n学历：${educationOptions[educationIndex.value]}\n求职意向：${userInfo.jobIntention}\n工作经验：${userInfo.experience || '0'}年\n技能特长：${userInfo.skills}\n自我评价：${userInfo.selfEvaluation}`
		};
		
		// 发送请求到后端AI接口
		const response = await uni.request({
			url: 'http://127.0.0.1:8081/ai/chat', 
			method: 'POST',
			data: requestData,
			header: {
				'content-type': 'application/json'
			}
		});
		
		// 处理响应数据
		if (response.statusCode === 200 && response.data) {
			// 保存原始AI回答
			aiResponseText.value = typeof response.data === 'string' 
				? response.data 
				: JSON.stringify(response.data, null, 2);
			
			// 尝试从返回的文本中提取JSON部分
			try {
				let jsonData;
				if (typeof response.data === 'string') {
					// 尝试从文本中提取JSON
					const jsonMatch = response.data.match(/\{[\s\S]*\}/); // 匹配最外层的大括号及其内容
					if (jsonMatch) {
						jsonData = JSON.parse(jsonMatch[0]);
					} else {
						throw new Error('无法从AI回答中提取JSON数据');
					}
				} else {
					// 如果已经是对象，直接使用
					jsonData = response.data;
				}
				
				// 解析技能列表
				resumeData.skills = Array.isArray(jsonData.skills) 
					? jsonData.skills 
					: userInfo.skills.split(',').map(skill => skill.trim());
				
				// 设置工作经历
				resumeData.workExperience = Array.isArray(jsonData.workExperience) 
					? jsonData.workExperience 
					: [];
				
				// 设置教育背景
				resumeData.education = Array.isArray(jsonData.education) 
					? jsonData.education 
					: [{
						school: '根据您的学历自动生成',
						time: '20XX年 - 20XX年',
						major: userInfo.major
					}];
				
				// 设置自我评价
				resumeData.selfEvaluation = jsonData.selfEvaluation || userInfo.selfEvaluation;
				
				// 设置简历标题
				resumeData.title = jsonData.title || `${userInfo.name}的个人简历`;
				
			} catch (parseError) {
				console.error('解析AI回答失败:', parseError);
				
				// 解析失败时使用默认值
				resumeData.skills = userInfo.skills.split(',').map(skill => skill.trim());
				resumeData.workExperience = [];
				resumeData.education = [{
					school: '根据您的学历自动生成',
					time: '20XX年 - 20XX年',
					major: userInfo.major
				}];
				resumeData.selfEvaluation = userInfo.selfEvaluation;
				resumeData.title = `${userInfo.name}的个人简历`;
			}
			
			// 显示生成的简历
			resumeGenerated.value = true;
			
			// 发送简历数据到后端保存
			sendResumeToBackend();
			
			uni.showToast({
				title: '简历生成成功',
				icon: 'success'
			});
		} else {
			throw new Error('生成简历失败');
		}
	} catch (error) {
		console.error('生成简历出错:', error);
		uni.showToast({
			title: '生成简历失败，请重试',
			icon: 'none'
		});
	} finally {
		// 无论成功失败，都关闭生成中状态
		isGenerating.value = false;
	}
}

// 发送简历数据到后端保存
async function sendResumeToBackend() {
	try {
		// 准备要发送的数据
		const resumeSubmitData = {
			user: userStore.getUserName || userInfo.name,
			userId: userStore.getUserId || 0,
			userInfo: { ...userInfo, education: educationOptions[educationIndex.value] },
			resumeData: { ...resumeData },
			aiResponse: aiResponseText.value
		};
		
		// 发送到后端保存
		const response = await uni.request({
			url: 'http://localhost:8088/UserAppLogin/resume', 
			method: 'POST',
			data: resumeSubmitData,
			header: {
				'content-type': 'application/json'
			}
		});
		
		console.log('简历保存结果:', response);
	} catch (error) {
		console.error('保存简历失败:', error);
	}
}

// 分享简历
function shareResume() {
	uni.showToast({
		title: '分享功能开发中',
		icon: 'none'
	});
}

// 重置表单，返回编辑状态
function resetForm() {
	resumeGenerated.value = false;
}
</script>

<style>
.resume-container {
	padding: 20px;
	background-color: #f8f8f8;
	min-height: 100vh;
}

.header {
	text-align: center;
	margin-bottom: 30px;
}

.title {
	font-size: 24px;
	font-weight: bold;
	color: #333;
}

.form-container {
	background-color: #fff;
	border-radius: 10px;
	padding: 20px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-item {
	margin-bottom: 20px;
}

.label {
	display: block;
	font-size: 16px;
	color: #333;
	margin-bottom: 8px;
}

.input {
	width: 100%;
	height: 40px;
	border: 1px solid #ddd;
	border-radius: 5px;
	padding: 0 10px;
	font-size: 16px;
	background-color: #f9f9f9;
}

.textarea {
	width: 100%;
	height: 100px;
	border: 1px solid #ddd;
	border-radius: 5px;
	padding: 10px;
	font-size: 16px;
	background-color: #f9f9f9;
}

.picker-text {
	height: 40px;
	line-height: 40px;
}

.submit-btn {
	width: 100%;
	height: 45px;
	line-height: 45px;
	background-color: #007aff;
	color: #fff;
	border-radius: 5px;
	font-size: 18px;
	margin-top: 20px;
}

.submit-btn[disabled] {
	background-color: #cccccc;
}

.loading-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	z-index: 999;
}

.loading-spinner {
	width: 50px;
	height: 50px;
	border: 5px solid #f3f3f3;
	border-top: 5px solid #007aff;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

.loading-text {
	color: #fff;
	margin-top: 20px;
	font-size: 16px;
}

/* 简历结果容器 */
.resume-result-container {
	max-height: calc(100vh - 80px);
}

/* 简历结果样式 */
.resume-result {
	background-color: #fff;
	border-radius: 10px;
	padding: 20px;
	box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.resume-header {
	text-align: center;
	margin-bottom: 30px;
	border-bottom: 2px solid #007aff;
	padding-bottom: 15px;
}

.resume-title {
	font-size: 22px;
	font-weight: bold;
	color: #333;
}

.resume-section {
	margin-bottom: 25px;
}

.section-title {
	font-size: 18px;
	font-weight: bold;
	color: #007aff;
	margin-bottom: 10px;
	padding-bottom: 5px;
	border-bottom: 1px solid #eee;
}

.info-row {
	margin-bottom: 8px;
	display: flex;
	flex-wrap: wrap;
}

.info-label {
	width: 80px;
	font-weight: bold;
	color: #666;
}

.info-value {
	flex: 1;
	color: #333;
}

.skill-item {
	padding: 4px 0;
}

.experience-item, .education-item {
	margin-bottom: 15px;
	padding-bottom: 15px;
	border-bottom: 1px dashed #eee;
}

.exp-title, .edu-school {
	font-weight: bold;
	font-size: 16px;
	color: #333;
	margin-bottom: 5px;
}

.exp-time, .edu-time {
	color: #999;
	font-size: 14px;
	margin-bottom: 5px;
}

.exp-desc, .edu-major {
	color: #666;
	font-size: 14px;
	line-height: 1.5;
}

/* AI回答展示区域 */
.ai-response-section {
	margin-top: 30px;
	background-color: #f9f9f9;
	border-radius: 8px;
	padding: 15px;
}

.ai-response-container {
	max-height: 200px;
	overflow-y: auto;
	padding: 10px;
	border: 1px solid #eee;
	border-radius: 5px;
	background-color: #fff;
}

.ai-response-text {
	font-size: 14px;
	line-height: 1.5;
	color: #666;
	white-space: pre-wrap;
	word-break: break-word;
}

/* 按钮组 */
.button-group {
	display: flex;
	justify-content: space-between;
	margin-top: 20px;
}

.back-btn, .share-btn {
	width: 48%;
	height: 45px;
	line-height: 45px;
	border-radius: 5px;
	font-size: 16px;
}

.back-btn {
	background-color: #f0f0f0;
	color: #333;
}

.share-btn {
	background-color: #007aff;
	color: #fff;
}
</style>
